package com.sailfish.springbootdemo.controller.db2;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.service.db2.PcbConfigService;
import com.sailfish.springbootdemo.service.db2.PcbMaterialService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/pcbMaterial")
public class PcbMaterialController {

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;
    /*@Value("${personal.config.file.host-prefix-url}")
    private String hostPrefixUrl ;*/

    @Autowired
    private PcbMaterialService pcbMaterialService;

    @Autowired
    private PcbConfigService PcbConfigService;
    //获取板材参数列表
    @PostMapping("/getAllPcbMaterialParam")
    public Result getAllPcbMaterialParam(Integer status) {
        PcbMaterialParam param = new PcbMaterialParam();
        param.setStatus(status);
        List<PcbMaterialParam> allPcbMaterialParam = pcbMaterialService.getAllPcbMaterialParam(param);
        return ResultUtil.success(allPcbMaterialParam);
    }

    //添加或更新板材参数列表
    @PostMapping("/insertOrUpdatePcbMaterialParam")
    public Result insertOrUpdatePcbMaterialParam(Integer pcbMaterialParamId, String paramName, String paramNameEn, String paramKey, Integer paramType, Integer isRequired, String paramOptions, String remark, Integer status, Integer sort) {

        PcbMaterialParam param = new PcbMaterialParam();
        if (StringUtils.isBlank(paramName) && StringUtils.isBlank(paramNameEn)) {
            return ResultUtil.error(500, "参数名为空", "", null);
        }
        param.setPcbMaterialParamId(pcbMaterialParamId);
        param.setParamName(paramName);
        param.setParamNameEn(paramNameEn);
        param.setParamKey(paramKey);
        param.setParamType(paramType);
        param.setIsRequired(isRequired);
        param.setParamOptions(paramOptions);
        param.setRemark(remark);
        param.setStatus(status);
        param.setSort(sort);
        if (pcbMaterialParamId == null) {
            param.setCreateTime(new Date());
        } else {
            param.setUpdateTime(new Date());
        }
        return pcbMaterialService.insertOrUpdatePcbMaterialParam(param);
    }
    // 更新或插入pcb板材公告
    @PostMapping("/insertOrUpdatePcbMaterialBulletin")
    @Transactional(transactionManager = "MysqlTransactionManager1")
    public Result insertOrUpdatePcbMaterialBulletin(@RequestBody String data) {
        try {
            JSONArray jsonArray = JSONObject.parseArray(JSONObject.parseObject(data).getString("attr_value"));

            // 获取现有公告
            List<PcbConfig> bulletinCfgs = PcbConfigService.getBulletinCfg();
            int existingBulletinsCount = bulletinCfgs == null ? 0 : bulletinCfgs.size();

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                String bulletinValue = jsonObject.getString("attrValue");
                if (StringUtils.isEmpty(bulletinValue)) {
                    return ResultUtil.error(500, "公告内容为空", "null bulletin", null);
                } else if (bulletinValue.length() >= 100) {
                    return ResultUtil.error(500, "公告内容过长（不超过100个字符）", "too long for bulletin", null);
                }

                PcbConfig param = new PcbConfig();
                param.setAttrValue(bulletinValue);
                Date time = new Date();
                param.setUpdateTime(time);

                // 尝试获取公告ID，如果存在则为更新操作，否则为插入操作
                Integer id = jsonObject.getInteger("id");
                if (id != null && id > 0) {
                    // 设置ID以进行更新操作
                    param.setId(id);
                    PcbConfigService.update(param); // 更新公告
                } else {
                    // 插入新的公告配置
                    // 设置公告名称，基于现有公告数量+当前索引
                    int newIndex = existingBulletinsCount;
                    existingBulletinsCount++;
                    if(newIndex >= 5)
                    {
                        return ResultUtil.error(500, "添加这些公告后总数量将超过5个", "total bulletins will exceed 5 after insertion", null);
                    }
                    param.setAttrName("pcbMaterialBulletin" + newIndex);
                    PcbConfigService.insert(param); // 插入公告
                }
            }
            return ResultUtil.success("板材公告更新或插入成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/deletePcbMaterialBulletin")
    @Transactional(transactionManager = "MysqlTransactionManager1")
    public Result deletePcbMaterialBulletin(@RequestBody String data){
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer idToDelete = jsonObject.getInteger("id");

            if (idToDelete == null || idToDelete <= 0) {
                return ResultUtil.error(500, "无效的公告ID", "Invalid bulletin ID", null);
            }

            // 获取所有现有公告
            List<PcbConfig> bulletinCfgs = PcbConfigService.getBulletinCfg();
            if (bulletinCfgs == null || bulletinCfgs.isEmpty()) {
                return ResultUtil.error(500, "没有找到任何公告", "No bulletins found", null);
            }

            // 找到并删除指定ID的公告
            boolean foundAndDeleted = false;
            for (int i = 0; i < bulletinCfgs.size(); i++) {
                PcbConfig bulletin = bulletinCfgs.get(i);
                if (bulletin.getId().equals(idToDelete)) {
                    PcbConfigService.delete(bulletin.getId()); // 删除公告
                    bulletinCfgs.remove(i);
                    foundAndDeleted = true;
                    break;
                }
            }

            if (!foundAndDeleted) {
                return ResultUtil.error(500, "未找到指定ID的公告", "Bulletin not found with the given ID", null);
            }

            // 重新排序并更新公告名称
            for (int newIndex = 0; newIndex < bulletinCfgs.size(); newIndex++) {
                PcbConfig bulletin = bulletinCfgs.get(newIndex);
                bulletin.setAttrName("pcbMaterialBulletin" + newIndex);
                PcbConfigService.update(bulletin); // 更新公告名称
            }

            return ResultUtil.success("公告删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    // 获取pcb板材公告
    @PostMapping("/getPcbMaterialBulletin")
    public Result getPcbMaterialBulletin() {
        try {
            List<PcbConfig> bulletinCfgs = PcbConfigService.getBulletinCfg();
            if(!Objects.isNull(bulletinCfgs) && !bulletinCfgs.isEmpty())
            {
                return ResultUtil.success(bulletinCfgs);
            }else{
                return ResultUtil.error(500, "pcb板材公告不存在", "pcb material bulletin dosen't exist", null);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
    //删除板材参数列表
    @PostMapping("/deletePcbMaterialParam")
    public Result deletePcbMaterialParam(Integer id) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "", null);
        }
        return pcbMaterialService.deletePcbMaterialParam(id);
    }

    //判断能否删除
    @PostMapping("/checkPcbMaterialParamHasData")
    public Result checkPcbMaterialParamHasData(Integer id) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "", null);
        }
        return pcbMaterialService.checkPcbMaterialParamHasData(id);
    }

    //获取板材库
    @PostMapping("/getAllPcbMaterialLibrary")
    public Result getAllPcbMaterialLibrary(@RequestBody String data) {//Integer materialStatus
        List<PcbMaterialLibrary> params = null;
        if(data != null)
        {
            try{
                JSONObject jsonObject = JSONObject.parseObject(data);

                String searchValueElect = jsonObject.getString("paramValue0");//电气性能等级筛选
                String searchValueBoardMaterial = jsonObject.getString("paramValue1");//板材筛选
                String searchValueMaxLayer = jsonObject.getString("paramValue2");//最大层数
                String searchValueMaxThick = jsonObject.getString("paramValue3");//最大板厚
                String searchK0 = null;
                String searchK1 = null;
                String searchK2 = null;
                String searchK3 = null;
                PcbMaterialParam temp = pcbMaterialService.getByParamName("电气性能等级");
                if(temp != null)
                {
                    searchK0 = temp.getParamKey();
                }
                temp = pcbMaterialService.getByParamName("板材");
                if(temp != null)
                {
                    searchK1 = temp.getParamKey();
                }
                temp = pcbMaterialService.getByParamName("最大层数");
                if(temp != null)
                {
                    searchK2 = temp.getParamKey();
                }
                temp = pcbMaterialService.getByParamName("最大板厚/mm");
                if(temp != null)
                {
                    searchK3 = temp.getParamKey();
                }

                if(!StringUtils.isBlank(searchK0)){
                    params = new ArrayList<>();
                    PcbMaterialLibrary search = new PcbMaterialLibrary();
                    search.setParamKey(searchK0);
                    search.setParamValue(searchValueElect);
                    params.add(search);
                }

                if(!StringUtils.isBlank(searchK1)){
                    PcbMaterialLibrary search = new PcbMaterialLibrary();
                    search.setParamKey(searchK1);
                    search.setParamValue(searchValueBoardMaterial);
                    if(params != null)
                    {
                        params.add(search);}
                    else{
                        params = new ArrayList<>();
                        params.add(search);
                    }
                }

                if(!StringUtils.isBlank(searchK2)){
                    PcbMaterialLibrary search = new PcbMaterialLibrary();
                    search.setParamKey(searchK2);
                    search.setParamValue(searchValueMaxLayer);
                    if(params != null)
                    {
                        params.add(search);}
                    else{
                        params = new ArrayList<>();
                        params.add(search);
                    }
                }

                if(!StringUtils.isBlank(searchK3)){
                    PcbMaterialLibrary search = new PcbMaterialLibrary();
                    search.setParamKey(searchK3);
                    search.setParamValue(searchValueMaxThick);
                    if(params != null)
                    {
                        params.add(search);}
                    else{
                        params = new ArrayList<>();
                        params.add(search);
                    }
                }
            }catch (Exception e)
            {
                e.printStackTrace();
                return ResultUtil.error(500, e.getMessage(), e.getLocalizedMessage(), null);
            }

        }

        List<MaterialInfo> allPcbMaterialData = pcbMaterialService.getAllPcbMaterialLibrary(params);
        return ResultUtil.success(allPcbMaterialData);
    }

    //获取板材列表
    @PostMapping("/getMaterialList")
    public Result getMaterialList() {
        List<PcbMaterialLibrary> materialList = pcbMaterialService.getMaterialList();
        return ResultUtil.success(materialList);

    }

    //添加或更新板材库
    @PostMapping("/insertOrUpdatePcbMaterialLibrary")
    public Result insertOrUpdatePcbMaterialLibrary(@RequestBody String data) {
        return pcbMaterialService.insertOrUpdatePcbMaterialLibrary(data);
    }

    //删除板材库
    @PostMapping("/deletePcbMaterialLibrary")
    public Result deletePcbMaterialLibrary(String rowKey) {
        if (StringUtils.isBlank(rowKey)) {
            return ResultUtil.error(500, "参数rowKey为空", "", null);
        }
        return pcbMaterialService.deletePcbMaterialLibrary(rowKey);
    }

    //提交认证
    @PostMapping("/submitPcbMaterialData")
    public Result submitPcbMaterialData(Integer pcbFactoryMaterialId, String approver, Integer materStatus, String remark, Integer openStatus) {
        if (pcbFactoryMaterialId == null) {
            return ResultUtil.error(500, "参数pcbFactoryMaterialId为空", "param pcbFactoryMaterialId is null", null);
        }
        if (materStatus == null) {
            return ResultUtil.error(500, "参数materStatus为空", "param materStatus is null", null);
        }
        if (!StringUtils.isBlank(approver)) {
            if (approver.endsWith(",")) {
                approver = approver.substring(0, approver.length() - 1);
            }
        }
        return pcbMaterialService.updatePcbMaterialFactoryStatus(pcbFactoryMaterialId, approver, materStatus, remark, openStatus);
    }

    //下载板材库
    @PostMapping("/downloadPcbMaterialFile")
    public Result downloadPcbMaterialFile(Integer id) {
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "param id is null", null);
        }
        return pcbMaterialService.getPcbMaterialFileById(id);
    }

    @PostMapping("/insertOrUpdatePcbMaterialLibraryAndFactory")
    public Result insertOrUpdatePcbMaterialLibraryAndFactory(@RequestBody String data) {

        return pcbMaterialService.insertOrUpdatePcbMaterialLibraryAndFactory(data);
    }

    @PostMapping("/insertOrUpdatePcbMaterialFactory")
    public Result insertOrUpdatePcbMaterialFactory(@RequestBody String data) {

        return pcbMaterialService.insertOrUpdatePcbMaterialFactory(data);
    }

    @PostMapping("getPcbMaterialLibraryAndFactory")
    public Result getPcbMaterialLibraryAndFactory(String rowKey) {
        if (StringUtils.isBlank(rowKey)) {
            return ResultUtil.error(500, "参数rowKey为空", "param rowKey is null", null);
        }

        List<PcbMaterialLibraryAndFactory> pcbMaterialLibraryAndFactory = pcbMaterialService.getPcbMaterialLibraryAndFactory(rowKey);
        return ResultUtil.success(pcbMaterialLibraryAndFactory);
    }

    @PostMapping("/getPcbMaterialAndFactoryData")
    public Result getPcbMaterialAndFactoryData(Integer factoryId, String rowKey, Integer materialStatus, String type) {
        if (factoryId == null) {
            return ResultUtil.error(500, "参数factoryId为空", "param factoryId is null", null);
        }
        Integer userId = null;
        if (type != null && type.equals("approve")) {
            String userId1 = UserHeaderHolder.getUserId();
            userId = Integer.parseInt(userId1);
        }
        List<PcbMaterialFactory> pcbMaterialAndFactoryData = pcbMaterialService.getPcbMaterialAndFactoryData(factoryId, rowKey, materialStatus, userId);
        return ResultUtil.success(pcbMaterialAndFactoryData);
    }

    @PostMapping("/getPcbMaterialData")
    public Result getPcbMaterialData() {
        List<PcbMaterialLibrary> pcbMaterialAndFactoryData = pcbMaterialService.getPcbMaterialData(null);
        return ResultUtil.success(pcbMaterialAndFactoryData);
    }


    /**
     * 上传图片
     *
     * @param req
     * @return
     */
    @PostMapping("/uploadFile")
    public Result uploadFile(HttpServletRequest req) {
        try {

            Map<String, String> map = new HashMap<>();
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile file = mRequest.getFile("file");
            if (file == null && file.getSize() == 0) {
                return ResultUtil.error(500, "文件上传错误，重新上传", "文件上传错误，重新上传", null);
            }

            //获取项目目录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            File folder = new File(fileSaveUrl + "\\commonUploadFiles\\pcb\\" + format);

            String filePath = "";
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID() +
                    oldName.substring(oldName.lastIndexOf("."));

            file.transferTo(new File(folder, newName));
            filePath = "commonUploadFiles\\pcb\\" + format + "\\" + newName;
//            map.put("name", newName);
            map.put("oldName", oldName);
            map.put("relatePath", filePath);
            //map.put("url", hostPrefixUrl + filePath);
            return ResultUtil.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @PostMapping("/submitFile")
    public Result submitFile(@RequestBody String data) {
        return pcbMaterialService.addFile(data);
    }

    @PostMapping("/outputPcbMaterialData")
    public Result outputMatchFactoryValue () {
        Result result = pcbMaterialService.outputPcbMaterialData();
        if (result.getCode().equals(200)) {
            try {
                String filepath = (String) result.getData();
                File file = new File(filepath);
                String fname = file.getName();
                byte[] bytedata = null;
                InputStream in = new FileInputStream(file);  //InputStream in = url.openStream();
                bytedata = new byte[in.available()];
                in.read(bytedata);
                in.close();
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString(bytedata);

                Map<String, Object> map = new HashMap<>();
                map.put("base64", base64);
                map.put("fileName", fname);
                return ResultUtil.success(map);

            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
        } else {
            return result;
        }
    }

    /*
    导出板材能力
     */
    @PostMapping("/outputPcbMaterialLibrary")
    public Result outputPcbMaterialLibrary() {
        Result result = pcbMaterialService.outputPcbBoardMaterialAbility();
        if (result.getCode().equals(200)) {
            try {
                String filepath = (String) result.getData();
                File file = new File(filepath);
                String fname = file.getName();
                byte[] bytedata = null;
                InputStream in = new FileInputStream(file);
                bytedata = new byte[in.available()];
                in.read(bytedata);
                in.close();
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString(bytedata);

                Map<String, Object> map = new HashMap<>();
                map.put("base64", base64);
                map.put("fileName", fname);
                return ResultUtil.success(map);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
        } else {
            return result;
        }
    }

    @PostMapping("/getElectBehaveList")
    public Result getElectBehaveList() {
        List<String> materialList = pcbMaterialService.getElectBehaveList();
        return ResultUtil.success(materialList);
    }

    @PostMapping("/outputSpecialProcessParam")
    public Result outputSpecialProcessParam(String version) {
        Result result = pcbMaterialService.outputPcbMaterialLibrary();
        if (result.getCode().equals(200)) {
            try {
                String filepath = (String) result.getData();
                File file = new File(filepath);
                String fname = file.getName();
                byte[] bytedata = null;
                InputStream in = new FileInputStream(file);
                bytedata = new byte[in.available()];
                in.read(bytedata);
                in.close();
                Base64.Encoder encoder = Base64.getEncoder();
                String base64 = encoder.encodeToString(bytedata);

                Map<String, Object> map = new HashMap<>();
                map.put("base64", base64);
                map.put("fileName", fname);
                return ResultUtil.success(map);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
            }
        } else {
            return result;
        }
    }
}
